package com.che.libcommon.ui;

import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;

public class NavTabController {

  private FragmentManager fragmentManager;

  private @IdRes int containerId;

  private FragmentProvider fragmentProvider;

  private String currentFragmentTag;

  private OnChangeCallback onChangeCallback;

  private boolean useDefaultAnim;

  public NavTabController(FragmentProvider fragmentProvider,FragmentManager fragmentManager,@IdRes int containerId) {
    this.fragmentProvider = fragmentProvider;
    this.fragmentManager = fragmentManager;
    this.containerId = containerId;
  }

  public NavTabController(FragmentProvider fragmentProvider,FragmentManager fragmentManager,@IdRes int containerId,boolean useDefaultAnim) {
    this.fragmentProvider = fragmentProvider;
    this.fragmentManager = fragmentManager;
    this.containerId = containerId;
    this.useDefaultAnim = useDefaultAnim;
  }

  public Fragment show(String tag){
    return show(tag,0,0);
  }


  public Fragment show(String tag,@AnimRes int animIn,@AnimRes int animOut){
    FragmentTransaction ft = fragmentManager.beginTransaction();
    Fragment fragment = findFragment(tag);
    if (fragment == null) {
      fragment = fragmentProvider.getFragment(tag);
    }

    if (fragment == null){
      return null;
    }

    if (!fragment.isAdded()){
      ft.add(containerId,fragment,tag);
    }

    Fragment currentFragment = getCurrentFragment();
    if (currentFragment != null){
      ft.hide(currentFragment);
    }

    if (animIn != 0 && animOut != 0){
      ft.setCustomAnimations(animIn,animOut);
    }else if (useDefaultAnim){
      ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    ft.show(fragment);
    currentFragmentTag = tag;
    ft.commitAllowingStateLoss();

    if (onChangeCallback != null){
      onChangeCallback.onShow(tag);
    }
    return fragment;
  }

  public Fragment getCurrentFragment(){
    return currentFragmentTag != null ? findFragment(currentFragmentTag):null;
  }

  public Fragment findFragment(String tag){
    return fragmentManager.findFragmentByTag(tag);
  }


  public boolean isShowing(String tag){
    Fragment currentFragment = getCurrentFragment();

    return currentFragment != null && TextUtils.equals(currentFragment.getTag(),tag);
  }

  public void setOnChangeCallback(OnChangeCallback onChangeCallback) {
    this.onChangeCallback = onChangeCallback;
  }

  public boolean canBack(){

    int b = fragmentManager.getBackStackEntryCount();

    Log.e("tab", "canBack --> "+b);

    return false;
  }

  public interface FragmentProvider{
    Fragment getFragment(String tag);
  }

  public interface OnChangeCallback{
    void onShow(String tag);
  }

}
